package com.gaoyi.basemodule.baseact;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;

import com.gaoyi.basemodule.basevm.BaseViewModel;
import com.gaoyi.basemodule.baseCallback.IView;

import java.lang.reflect.ParameterizedType;

public abstract class BaseActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends BasePermissionActivity {

    protected V mBinding;
    protected VM mViewModel;
    protected FragmentActivity mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
        mContext = this;
        mBinding = DataBindingUtil.setContentView(this, getLayoutId());
        mViewModel = new ViewModelProvider(this).get(getViewModelClass());
        if (this instanceof IView) {
            mViewModel.attachView((IView) this);
        }
        getLifecycle().addObserver(mViewModel);
        mBinding.setLifecycleOwner(this);
        mBinding.setVariable(initVariable(), mViewModel);
        initView();
        initLiveData();
        initData();
    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract int initVariable();

    protected abstract void initLiveData();

    protected abstract void initData();

    Class<VM> getViewModelClass() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        if (type == null) return null;
        return (Class<VM>) type.getActualTypeArguments()[1];
    }

    @Override
    protected void onDestroy() {
        mBinding.unbind();
        super.onDestroy();
    }
}
